#include "wg_loading.hpp"

WgLoading::WgLoading(QWidget* parent)
    : QDialog(parent)
{
    setWindowFlags(Qt::FramelessWindowHint | Qt::Tool | Qt::WindowStaysOnTopHint);
    setAttribute(Qt::WA_TranslucentBackground, true);
    init_ui();
}

void WgLoading::init_ui()
{
    setFixedSize(250, 250);
    frame_center = new QFrame(this);
    frame_center->setGeometry(10, 10, 230, 230);

    movie_loading = new QMovie(":/images/loading2.gif");
    movie_loading->setScaledSize(QSize(110, 110));
    movie_label = new QLabel(frame_center);
    movie_label->setGeometry(55, 35, 110, 110);
    movie_label->setScaledContents(true);
    movie_label->setMovie(movie_loading);
    movie_loading->start();

    label_tips = new QLabel(frame_center);
    label_tips->setGeometry(5, 130, 220, 50);
    label_tips->setAlignment(Qt::AlignCenter | Qt::AlignHCenter);
    label_tips->setObjectName("lab_load_tips");
    label_tips->setText("loading");

    btn_cancel = new QPushButton(frame_center);
    btn_cancel->setObjectName("btn_load_cancel");
    btn_cancel->setText("close loading");
    btn_cancel->setGeometry(25, 180, 180, 35);
    btn_cancel->setEnabled(true);
    connect(btn_cancel, &QPushButton::clicked, this, &WgLoading::btn_cancel_clicked);

    QGraphicsDropShadowEffect* shadow = new QGraphicsDropShadowEffect(this);
    shadow->setOffset(0, 0);
    shadow->setColor(QColor(32, 101, 165));
    shadow->setBlurRadius(15);
    setGraphicsEffect(shadow);

    QString qss_style;
    if(SgtStyle::getInstance()->get_style(qss_style,SgtStyle::SORT::GLOBAL)){
        setStyleSheet(qss_style);
    }
}

void WgLoading::set_txt_tips(const QString txt)
{
    label_tips->setText(txt);
}

void WgLoading::enable_cancel(const bool enable)
{
    btn_cancel->setEnabled(enable);
}

void WgLoading::move_center(QWidget* parent)
{
    if (parent != nullptr && parent != NULL)
    {
        int nParentWidth = parent->width();
        int nParentHeigth = parent->height();

        int nWidth = this->width();
        int nHeight = this->height();

        int nParentX = parent->x();
        int nParentY = parent->y();

        int x = (nParentX + (nParentWidth - nWidth) / 2);
        int y = (nParentY + (nParentHeigth - nHeight) / 2);
        this->move(x, y);
    }
}

void WgLoading::btn_cancel_clicked()
{
    emit cancel_waiting();
    this->done(USER_CANCEL);
}

void WgLoading::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(QBrush(Qt::white));
    painter.setPen(Qt::transparent);
    QRect rect = this->rect();
    rect.setLeft(9);
    rect.setTop(9);
    rect.setWidth(rect.width() - 9);
    rect.setHeight(rect.height() - 9);
    painter.drawRoundedRect(rect, 8, 8);
    QWidget::paintEvent(event);
}

WgLoading::~WgLoading()
{
    delete movie_loading;
    delete movie_label;
    delete label_tips;
    delete btn_cancel;
    delete frame_center;
}